import re
import os

def main():
    input_file = os.path.join(os.path.dirname(__file__), 'ry_20250522.sql')
    output_file = os.path.join(os.path.dirname(__file__), 'ry_20250522_snowflake.sql')

    with open(input_file, 'r', encoding='utf-8') as f:
        sql = f.read()

    # 1. 只处理表结构主键自增字段和表级auto_increment
    def process_create_table(sql):
        def field_replacer(match):
            field = match.group(0)
            field = re.sub(r'bigint\(20\)\s+not null\s+auto_increment', 'varchar(20) not null', field, flags=re.IGNORECASE)
            field = re.sub(r'auto_increment', '', field, flags=re.IGNORECASE)
            return field
        def table_replacer(table_match):
            table_sql = table_match.group(0)
            table_sql = re.sub(r'^\s*\w*id\s+bigint\(20\)\s+not null\s+auto_increment.*$', field_replacer, table_sql, flags=re.MULTILINE|re.IGNORECASE)
            # 去除表级auto_increment=xxx
            table_sql = re.sub(r'(engine=innodb)\s+auto_increment=\d+', r'\1', table_sql, flags=re.IGNORECASE)
            # 其他bigint(20) id字段（如外键）也转varchar(20)
            table_sql = re.sub(r'(\b\w*id\b)\s+bigint\(20\)', r'\1 varchar(20)', table_sql, flags=re.IGNORECASE)
            return table_sql
        return re.sub(r'create table[\s\S]*?\)[^;]*;', table_replacer, sql, flags=re.IGNORECASE)

    sql = process_create_table(sql)

    sql = re.sub(r'\s+\n', '\n', sql)
    sql = re.sub(r'\n{3,}', '\n\n', sql)

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(sql)
    print(f'转换完成，输出文件: {output_file}')

if __name__ == '__main__':
    main() 